package com.jixi.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jixi.common.exception.PowerFailedException;
import com.jixi.common.result.PageResult;
import com.jixi.common.result.Result;
import com.jixi.common.utils.Md5Util;
import com.jixi.mapper.AccountMapper;
import com.jixi.mapper.EducationMapper;
import com.jixi.pojo.dto.EducationLoginDto;
import com.jixi.pojo.dto.EducationRegisterDto;
import com.jixi.pojo.entity.Account;
import com.jixi.pojo.entity.Education;
import com.jixi.service.EducationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Slf4j
@Service
public class EducationServiceImpl extends ServiceImpl<EducationMapper, Education> implements EducationService {
	
	@Autowired
	private EducationMapper educationMapper;
	
	@Autowired
	private AccountMapper accountMapper;
	
	/**
	 * 教育局注册
	 *
	 * @param educationRegisterDto 教育局注册Dto
	 * @return 注册结果
	 */
	@Override
	public Result educationRegister(EducationRegisterDto educationRegisterDto) {
		
		//先查登录的账号的权限
		Long loginEducationId = StpUtil.getLoginIdAsLong();
		//构造查询
		LambdaQueryWrapper<Education> queryWrapper = new LambdaQueryWrapper<>();
		//以id作为查询依据
		queryWrapper.eq(Education::getEducationId, loginEducationId);
		//获取实例
		Education loginEducation = educationMapper.selectOne(queryWrapper);
		//判断权限
		if (loginEducation.getEducationPower() != 1) {
			throw new PowerFailedException("权限不足");
		}
		
		Education education = new Education();
		BeanUtils.copyProperties(educationRegisterDto, education);
		log.info("注册信息：{}", education);
		education.setIsDeleted(0);
		education.setEducationPassword(Md5Util.getMD5String(education.getEducationPassword()));
		educationMapper.insert(education);
		return Result.success("注册成功");
	}
	
	/**
	 * 教育局登录
	 *
	 * @param educationLoginDto 教育局登录Dto
	 * @return 登录结果
	 */
	@Override
	public Result educationLogin(EducationLoginDto educationLoginDto) {
		log.info("登录请求:{}", educationLoginDto);
		String username = educationLoginDto.getEducationUsername();
		String password = Md5Util.getMD5String(educationLoginDto.getEducationPassword());
		//构造查询
		LambdaQueryWrapper<Education> queryWrapper = new LambdaQueryWrapper<>();
		//以username作为查询依据
		queryWrapper.eq(Education::getEducationUsername, username);
		//获取实例
		Education education = educationMapper.selectOne(queryWrapper);
		//判断账号密码（含判断删除）
		if (education == null || ! password.equals(education.getEducationPassword()) || education.getIsDeleted() == 1) {
			return Result.fail("账号或密码错误");
		}
		//查询禁用状态
		if (education.getStatus() == 0) {
			return Result.fail("账号已禁用，请联系超级管理员");
		}
		//登录
		StpUtil.login(education.getEducationId());
		return Result.success("登录成功");
	}
	
	/**
	 * 重置密码
	 *
	 * @param educationId   教育局id
	 * @param resetPassword 重置密码
	 * @return 重置结果
	 */
	@Override
	public Result educationResetPassword(Long educationId, String resetPassword) {
		//先查登录的账号的权限
		Long loginEducationId = StpUtil.getLoginIdAsLong();
		//构造查询
		LambdaQueryWrapper<Education> queryWrapper = new LambdaQueryWrapper<>();
		//以id作为查询依据
		queryWrapper.eq(Education::getEducationId, loginEducationId);
		//获取实例
		Education loginEducation = educationMapper.selectOne(queryWrapper);
		//判断权限
		if (loginEducation.getEducationPower() != 1) {
			throw new PowerFailedException("权限不足");
		}
		if (Objects.equals(educationId, loginEducationId)) {
			return Result.fail("不能重置自己的密码");
		}
		LambdaQueryWrapper<Education> queryWrapper1 = new LambdaQueryWrapper<>();
		queryWrapper1.eq(Education::getEducationId, educationId);
		Education education = educationMapper.selectOne(queryWrapper1);
		if (education.getOriginal() == 1) {
			return Result.fail("不能对初始账号进行操作");
		}
		education.setEducationPassword(Md5Util.getMD5String(resetPassword));
		education.setUpdateTime(DateTime.now());
		educationMapper.insertOrUpdate(education);
		//修改后踢下线
		StpUtil.logout(educationId);
		return Result.success("重置密码成功");
	}
	
	/**
	 * 修改密码
	 *
	 * @param oldPassword 旧密码
	 * @param newPassword 新密码
	 * @param rePassword  重复新密码
	 * @return 修改结果
	 */
	@Override
	public Result educationUpdatePassword(String oldPassword, String newPassword, String rePassword) {
		
		Long educationId = StpUtil.getLoginIdAsLong();
		
		//构造查询
		LambdaQueryWrapper<Education> queryWrapper = new LambdaQueryWrapper<>();
		//以id作为查询依据
		queryWrapper.eq(Education::getEducationId, educationId);
		//获取实例
		Education education = educationMapper.selectOne(queryWrapper);
		
		//判断
		if (! Md5Util.getMD5String(oldPassword).equals(education.getEducationPassword())) {
			return Result.fail("旧密码错误");
		}
		if (newPassword.equals(oldPassword)) {
			return Result.fail("新密码与旧密码不能相同");
		}
		if (! newPassword.equals(rePassword)) {
			return Result.fail("两次输入的新密码不一致");
		}
		
		//修改
		education.setEducationPassword(Md5Util.getMD5String(newPassword));
		education.setUpdateTime(DateTime.now());
		educationMapper.insertOrUpdate(education);
		//修改后踢下线
		StpUtil.logout(educationId);
		return Result.success("密码修改成功");
	}
	
	/**
	 * 获取教育局信息
	 *
	 * @return 教育局信息
	 */
	@Override
	public Education getEducationinfo() {
		Long educationId = StpUtil.getLoginIdAsLong();
		Education education = educationMapper.selectById(educationId);
		return education;
	}
	
	/**
	 * 教育局列表条件分页查询
	 *
	 * @param pageNum           页码
	 * @param pageSize          页大小
	 * @param educationNickname 教育局昵称
	 * @param educationPower    权限
	 * @param status            状态
	 * @return 教育局列表
	 */
	@Override
	public Result<PageResult> educationPage(
			Integer pageNum,
			Integer pageSize,
			String educationNickname,
			Integer educationPower,
			Integer status
	) {
		//分页构造器
		Page<Education> pageInfo = new Page<>(pageNum, pageSize);
		//条件构造器
		LambdaQueryWrapper<Education> queryWrapper = new LambdaQueryWrapper<>();
		//只查未删除的
		queryWrapper.eq(Education::getIsDeleted, 0);
		//添加可能有的过滤条件
		queryWrapper.like(educationNickname != null && !educationNickname.trim().isEmpty(), Education::getEducationNickname, educationNickname);
		queryWrapper.eq(educationPower != null, Education::getEducationPower, educationPower);
		queryWrapper.eq(status != null, Education::getStatus, status);
		//执行分页查询
		educationMapper.selectPage(pageInfo, queryWrapper);
		PageResult pageResult = new PageResult(pageInfo.getTotal(), pageInfo.getRecords());
		return Result.success(pageResult);
	}
	
	/**
	 * 修改权限
	 *
	 * @param educationId    教育局Id
	 * @param educationPower 权限
	 * @return 修改结果
	 */
	@Override
	public Result educationPermission(Long educationId, Integer educationPower) {
		//先查登录的账号的权限
		Long loginEducationId = StpUtil.getLoginIdAsLong();
		//构造查询
		LambdaQueryWrapper<Education> queryWrapper = new LambdaQueryWrapper<>();
		//以id作为查询依据
		queryWrapper.eq(Education::getEducationId, loginEducationId);
		//获取实例
		Education loginEducation = educationMapper.selectOne(queryWrapper);
		//判断权限
		if (loginEducation.getEducationPower() != 1) {
			throw new PowerFailedException("权限不足");
		}
		
		if (educationPower != 1 && educationPower != 2) {
			return Result.fail("权限值有误");
		}
		//不能修改自己的
		if (educationId.equals(loginEducationId)) {
			return Result.fail("不能修改自己的账号权限");
		}
		//执行修改
		LambdaQueryWrapper<Education> queryWrapper1 = new LambdaQueryWrapper<>();
		//只查未删除的
		queryWrapper1.eq(Education::getIsDeleted, 0);
		queryWrapper1.eq(Education::getEducationId, educationId);
		Education education = educationMapper.selectOne(queryWrapper1);
		if (education.getOriginal() == 1) {
			return Result.fail("不能对初始账号进行操作");
		}
		education.setEducationPower(educationPower);
		education.setUpdateTime(DateTime.now());
		educationMapper.insertOrUpdate(education);
		return Result.success("权限修改成功");
	}
	
	/**
	 * 修改状态
	 *
	 * @param educationId 教育局Id
	 * @param status      教育局状态
	 * @return 修改结果
	 */
	@Override
	public Result updateEducationStatus(Long educationId, Integer status) {
		//先查登录的账号的权限
		Long loginEducationId = StpUtil.getLoginIdAsLong();
		//构造查询
		LambdaQueryWrapper<Education> queryWrapper = new LambdaQueryWrapper<>();
		//以id作为查询依据
		queryWrapper.eq(Education::getEducationId, loginEducationId);
		//获取实例
		Education loginEducation = educationMapper.selectOne(queryWrapper);
		//判断权限
		if (loginEducation.getEducationPower() != 1) {
			throw new PowerFailedException("权限不足");
		}
		//不能修改自己的
		if (educationId.equals(loginEducationId)) {
			return Result.fail("不能修改自己的账号状态");
		}
		if (status != 1 && status != 0) {
			return Result.fail("状态值有误");
		}
		//执行修改
		LambdaQueryWrapper<Education> queryWrapper1 = new LambdaQueryWrapper<>();
		//只查未删除的
		queryWrapper1.eq(Education::getIsDeleted, 0);
		queryWrapper1.eq(Education::getEducationId, educationId);
		Education education = educationMapper.selectOne(queryWrapper1);
		if (education.getOriginal() == 1) {
			return Result.fail("不能对初始账号进行操作");
		}
		education.setStatus(status);
		education.setUpdateTime(DateTime.now());
		educationMapper.insertOrUpdate(education);
		return Result.success("状态修改成功");
	}
	
	/**
	 * 删除账号
	 *
	 * @param educationId 教育局id
	 * @return 删除结果
	 */
	@Override
	public Result deleteEducationById(Long educationId) {
		
		//先查登录的账号的权限
		Long loginEducationId = StpUtil.getLoginIdAsLong();
		//构造查询
		LambdaQueryWrapper<Education> queryWrapper = new LambdaQueryWrapper<>();
		//以id作为查询依据
		queryWrapper.eq(Education::getEducationId, loginEducationId);
		//获取实例
		Education loginEducation = educationMapper.selectOne(queryWrapper);
		
		//判断权限
		if (loginEducation.getEducationPower() != 1) {
			throw new PowerFailedException("权限不足");
		}
		
		//不能修改自己的
		if (educationId.equals(loginEducationId)) {
			return Result.fail("不能删除自己的账号");
		}
		
		//删之前先检查是否有账户绑定在该账号上
		LambdaQueryWrapper<Account> queryWrapper2 = new LambdaQueryWrapper<>();
		queryWrapper2.eq(Account::getIsDeleted, 0);
		queryWrapper2.eq(Account::getEducationId, educationId);
		Long count = accountMapper.selectCount(queryWrapper2);
		if (count != 0) {
			return Result.fail("该教育局账号下有 " + count + " 个账户绑定，无法删除");
		}
		
		//假删除
		LambdaQueryWrapper<Education> queryWrapper1 = new LambdaQueryWrapper<>();
		queryWrapper1.eq(Education::getEducationId, educationId);
		Education education = educationMapper.selectOne(queryWrapper1);
		if (education.getOriginal() == 1) {
			return Result.fail("不能删除初始管理员账号");
		}
		education.setIsDeleted(1);
		education.setUpdateTime(DateTime.now());
		educationMapper.insertOrUpdate(education);
		
		return Result.success("删除成功");
	}
	
	/**
	 * 修改信息
	 *
	 * @param educationNickname 教育局昵称
	 * @param educationTel      教育局电话
	 * @return 修改结果
	 */
	@Override
	public Result educationUpdateInfo(String educationNickname, String educationTel) {
		//根据登录状态获取id
		Long educationId = StpUtil.getLoginIdAsLong();
		//查询
		LambdaQueryWrapper<Education> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(Education::getEducationId, educationId);
		queryWrapper.eq(Education::getIsDeleted, 0);
		Education education = educationMapper.selectOne(queryWrapper);
		
		//修改
		education.setEducationNickname(educationNickname);
		education.setEducationTel(educationTel);
		education.setUpdateTime(DateTime.now());
		educationMapper.insertOrUpdate(education);
		
		return Result.success("修改成功");
	}
	
}
